<!--
 * @Author       : wfl
 * @LastEditors: wfl
 * @description  : 下拉角色树
 * @updateInfo   :
 * @Date         : 2022-11-03 14:39:34
 * @LastEditTime: 2023-04-14 14:47:06
-->

<script lang="ts" setup name="IkSelectRole">
import { ElMessage } from 'element-plus'
import { ikTree } from 'iking-utils'
import type { Ref } from 'vue'
import { useSelect } from './use-select-fun'
import { roleApi } from '@/MainApp/apis/role'

// 组件 v-model绑定
const value = defineModel({
  type: String || Array<String>,
  default: ''
})
const { handCheck, handSelect } = useSelect(value)
const expanded: Ref<string[]> = ref([])
// 角色数据
const roleData: Ref<Array<{ label: string; value: string; id: string; }>> = ref([])
roleApi.getRoleList().then(({ success, data, msg }) => {
  const fixData = data?.map((li: { name: any; id: any; }) => {
    return {
      ...li,
      label: li.name,
      value: li.id
    }
  })
  roleData.value = success
    ? ikTree.listToTree(fixData, { sort: 'sortOrder', needSort: true })
    : []
  // 默认展开一级
  expanded.value = roleData.value.map(v => v.id)
  if (!success)
    ElMessage.warning(msg)
})
</script>

<template>
  <!-- 使用组件时 因为存在 $attrs 所以支持所有组件本身props 事件 属性 等等 -->
  <el-tree-select
    v-model="value"
    v-bind="$attrs"
    :data="roleData"
    node-key="id"
    :check-on-click-node="true"
    :render-after-expand="false"
    :default-expanded-keys="expanded"
    @check="handCheck"
    @node-click="handSelect"
  />
</template>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
